/*
 *xxx 待封装到util工具包中
 ************************************************************************
 */
Ext.tree.createXMLTree = function(el, url, callback) {
    var tree = new Ext.tree.TreePanel({
        el: el,
        enableDD: true,
        autoScroll: true,
        animate: true,
        //frame: true, //使树的背景被蓝色填充
        rootVisible: false
    });
    var p = new Ext.data.HttpProxy({url: url, method: 'POST'});
    p.on("loadexception", function(t, o, response, e) {
        if (e) throw e;
        alert('读取数据出错，可能对应资源部不存在!');
    });
    p.load(null, {
        read: function(response) {
            var doc = response.responseXML;
            var xmlRoot = doc.documentElement || doc;
            var q = Ext.DomQuery;
            var maparray = q.selectValue('datamap', xmlRoot).replace(/\s/, '').split(',');
            var datamap = {};
            var root = new Ext.tree.AsyncTreeNode({
                text: 'ExtTreeRoot', 
                draggable:false, // disable root node dragging
                id:'ExtTreeRoot'
            });
            
            Ext.each(maparray, function(el) {
                var key = el.split('=')[1];
                var value = el.split('=')[0];
                datamap[key] = value;
            });
            var record = q.selectValue('objects', xmlRoot);
            var ns = q.select('/' + record, xmlRoot);
            Ext.each(ns ,function(el) {
                root.appendChild(Ext.tree.nodeFromXML(el, datamap, record, q));
            });

            tree.setRootNode(root);

            Ext.tree.Loaded = true;
        }
    }, callback || tree.render, tree);
    return tree;
};
/********************************************************************************/

/*
 *xxx 待封装到util工具包中
 *******************************************************************************
 */
Ext.tree.nodeFromXML = function(el, datamap, record, q) {
    if (el.nodeType != 1) return;

    //treenode init
    var id = q.selectValue(datamap['id'] ? datamap['id'] : 'id', el); 
    var text = q.selectValue(datamap['text'] ? datamap['text'] : 'text', el); 
    var url = q.selectValue(datamap['url'] ? datamap['url'] : 'url', el); 
    var checked = q.selectValue(datamap['checked'] ? datamap['checked'] : 'checked', el); 
    if (checked == 'true') {
        checked = true;
    } else if (checked == 'false') {
        checked = false;
    }
    var leaf = q.selectNode(record, el) ? false : true;

    var treeNode = new Ext.tree.TreeNode({
        id: id,
        text: text,
        leaf: leaf,
        checked: checked,
        param: {url: url},
        draggable: true
    });

    if (!leaf) {
        Ext.each(q.select('/*/' + record, el), function(elN) {
            treeNode.appendChild(Ext.tree.nodeFromXML(elN, datamap, record, q));
        })
    }
    return treeNode;
};
/********************************************************************************/


Ext.util.XML = new (function() {
    this.xmlToJson = function(xmlUrl) {
        var p = new Ext.data.HttpProxy({url: xmlUrl, method: 'POST'});
        var q = Ext.DomQuery;
        var jsonData = [];
        var setObject = function(el) {
            var tmp = {};
            Ext.each(el.childNodes, function(elNode) {
                if (elNode.hasChildNodes()) {
                    setObject(elNode);
                } else if (elNode.nodeType == 1) {
                    tmp[elNode.nodeName] = q.selectValue(elNode.nodeName, nsEl);
                    debugger;
                }
            });
            return tmp;
        };
        
        var createJsonData = function(ns, jsonData) {
            Ext.each(ns, function(nsEl) {
                var tmp = {};
                if (nsEl.hasChildNodes()) {
                    var childArray = setObject(nsEl);
                    if (childArray) {
                        tmp[nsEl.nodeName] = childArray;
                    }
                }
                /*
                Ext.each(map, function(eli) {
                    tmp[eli] = q.selectValue(eli ,el) ? q.selectValue(eli, el) : '';
                });
                if (q.select('children resource', el)) {
                    tmp['children'] = [];
                    createJsonData(m(q.selectNode('children' ,el)), tmp['children']);
                }
                */
                jsonData.push(tmp);
            });
        };
        
        p.load(null, {
            read: function(response) {
                var doc = response.responseXML;
                var xmlRoot = doc.documentElement || doc;
                var maparray = q.selectValue('datamap', xmlRoot).replace(/\s/, '').split(',');
                var map = {};
                Ext.each(maparray, function(el) {
                    var key = el.split('=>')[0];
                    var value = el.split('=>')[1];
                    map[key] = value;
                });
                
                var m = q.compile(q.selectValue('objects', xmlRoot).replace(/\s/, ''));
                var ns = m(xmlRoot);
                createJsonData(ns, jsonData);
            }
        }, function() {}, this);
    }
})();

Ext.util.Sail = new (function() {
    this.createWindow = function(width, height, url, modalable) {
        modalable = modalable && 1;
        var win = new Ext.Window({
            closable: true,
            width: 400,
            height: 300,
            maximizable: !modalable,
            minimizable: !modalable,
            plain: true,
            resizable: !modalable,
            modal: modalable,
            layout: 'fit',
            closeAction: 'close',
            html: '<iframe id="newwindow" src="' + url + '" width="100%" height="100%"></iframe>'
        });
        win.show();
    },

    this.swapTheme = function(theme, doc, smallable) {
        var flag = smallable == true ? true : false;
        if (!flag) {
            Ext.util.CSS.swapStyleSheet('theme', '/' + window.location.pathname.split('/', 2)[1] + '/support/resources/css/' + theme);
        }
        var existing = doc.getElementById('theme');

        if (existing) {
            existing.parentNode.removeChild(existing);
        }
        var ss = doc.createElement("link");
        ss.setAttribute("rel", "stylesheet");
        ss.setAttribute("type", "text/css");
        ss.setAttribute("id", "theme");
        ss.setAttribute("href", '/' + window.location.pathname.split('/', 2)[1] + '/support/resources/css/' + theme);
        doc.getElementsByTagName("head")[0].appendChild(ss);
    }
})();

Ext.util.Validation = new (function() {
    this.isValidFileName = function(filename) {
        filename = filename.split(/[\/\\]/).pop();
        if (/[_a-zA-Z0-9]+\.sail$/) {
            return true;
        } else {
            return false;
        }
    } 
})();
